package com.cd.works.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import javax.servlet.annotation.*;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cd.works.domain.Allservice;
import com.cd.works.domain.ErrorResponse;
import com.cd.works.domain.LogBean;
import com.cd.works.domain.Model;
import com.cd.works.domain.RandomNumbers;
import com.cd.works.domain.RegBean;
import com.cd.works.domain.TestJavaMail;
import com.cd.works.domain.TestTcpSms;
import com.google.gson.Gson;


/**
 * Servlet implementation class ControllerServlet
 */

@MultipartConfig(maxFileSize = 16177215)
public class ControllerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String FROM_EMAIL="vinodkumarbm.dvg@gmail.com";
	private static final String PWD_EMAIL="4SM09EC080";
	private final String USER_AGENT = "Mozilla/5.0";  
    /**
     * Default constructor. 
     */
    public ControllerServlet() {
        System.out.println("inside CS contr");
    }
    
    @Override
    public void init() throws ServletException {
    	System.out.println("inside init()");
    	
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("inside doGet()");
		process(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("inside doPost()");
		process(request,response);
	}
	
	@Override
	protected void doPut(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("inside doPut()");
		process(request,response);
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		
		Gson gson=new Gson();
		Model model=new Model();
		String uri=request.getRequestURI();
		if(uri.contains("/register")){
			PrintWriter out=response.getWriter();
//			HttpSession session=request.getSession(true);
			response.setContentType("application/json");
			RegBean rb=gson.fromJson(request.getReader(), RegBean.class);
			String result=model.register(rb);
			if(result.equals("SUCCESS")){
				
				String code=String.valueOf(RandomNumbers.randInt(0000, 9999));
				String to= rb.getEmail();
				 String from =FROM_EMAIL;
				 String pwd = PWD_EMAIL;
				 String subject= "CLICK DESIGNERS Verification Code";
				 String body= "Your Verication code is "+code;
				 TestJavaMail.send(to, from, pwd , subject, body);
//				 request.sendRedirect("http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=vishwaprasadpv@gmail.com:9900368788&senderID=TEST SMS&receipientno="+rb.getMobileNum()+"&dcs=0&msgtxt="+body+"&state=0");
//				 RequestDispatcher rd=request.getRequestDispatcher("sendMsg");
//				 rd.include(request, response);
//				 session.setAttribute("Code", code);
				 String url ="http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=vinodkumarbm.dvg@gmail.com:4sm09ec080&senderID=TEST SMS&receipientno="+rb.getMobileNum()+"&dcs=0&msgtxt="+body+"&state=0";
				 URL obj = new URL(url);
					URLConnection con =obj.openConnection();
					// optional default is GET
					con.connect();
					System.out.println("SMS SENT");
					
					
				 out.println("VERIFICATION_CODE_SENT_TO_MOBILE_EMAIL");
				 
			}else{
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				ErrorResponse error=new ErrorResponse();
				error.setMessage(result);
				error.setReason(result);
				out.println(gson.toJson(error));
			}
		}
		
		if(uri.contains("/verifyByCode")){
			PrintWriter out=response.getWriter();
			response.setContentType("application/json");
			
			HttpSession session=request.getSession(false);// dont create session bcaz already exists
			if(session!=null){
				String email=request.getParameter("email");
				String code=request.getParameter("code");
				String attrCode=(String) session.getAttribute("Code");
				
				if(code.equals(attrCode)){
					String result=model.verifyByCode(email);
					if(result.equals("INVALID_USER")){
						response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
						out.println(result);
					}else{
						out.println("SUCCESS");
						session.invalidate();
					}
					
				}else {
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
					out.println("Wrong Verification Code");
				}
			}else{
				out.println("Session Ended");
			}
			
			
	
		}
		
		
		if (uri.contains("/login")) {
			PrintWriter out=response.getWriter();
			response.setContentType("application/json");
			LogBean lb=gson.fromJson(request.getReader(), LogBean.class);
			
			String result=model.login(lb);
			
			if(result.equals("SUCCESS")){
				out.println("Login Success");
			}else{
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				out.println(result);
			}
		}
		if(uri.contains("senSMS")){
			PrintWriter out=response.getWriter();
			TestTcpSms.sendSMS();
		}
		
		if (uri.contains("/uploadImage1")) {
			PrintWriter out=response.getWriter();
			response.setContentType("text/html");
			
			Allservice service = new Allservice();
			int num = 0;

			try {
				//Create a factory for disk-based file items
				DiskFileItemFactory factory = new DiskFileItemFactory();
				//Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload(factory);
				//parse the request
				List items = upload.parseRequest(request);
				num = service.upload(items);
				if (num == 1) {
				out.println("<h3> File Uploaded Successfully </h3>");
				}else if (num == -1) {
				out.println("<h3><font color='red'> Please select the file</font></h3>");
				}else {
				out.println("<h3><font color='red'> Failure during File Upload</font></h3>");
				}
				} catch (Exception e) {
				}

		}
		
		if (uri.contains("/uploadImage")) {
			PrintWriter out=response.getWriter();
			int num = 0;
			InputStream inputStream = null;
			Part filePart=request.getPart("photo");
			if (filePart != null) {
	            // prints out some information for debugging
	            System.out.println(filePart.getName());
	            System.out.println(filePart.getSize());
	            System.out.println(filePart.getContentType());
	            
	             
	            // obtains input stream of the upload file
	            inputStream = filePart.getInputStream();
	            num=model.uploadImage(inputStream);
	            
				if (num == 1) {
				out.println("<h3> File Uploaded Successfully </h3>");
				}else if (num == -1) {
				out.println("<h3><font color='red'> Please select the file</font></h3>");
				}else {
				out.println("<h3><font color='red'> Failure during File Upload</font></h3>");
				}
	        }
			
		}
		
		if(uri.contains("/getImage")){
			response.setContentType("image/jpeg");
			String email=request.getParameter("email");
			byte[] barr=model.retriveImage(email);
			System.out.println("Ready to display");
			ServletOutputStream stream=response.getOutputStream();
			stream.write(barr);
		}
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("inside destroy()");
		
	}

}
